﻿using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using MessageCenter;
using System;
using System.Threading.Tasks;
using mc = MessageCenter;

namespace gRPCServer
{
    class MessageCenterImpl : mc.MessageCenter.MessageCenterBase
    {
        public override async Task<PublisherHandle> register(PublisherInfo request, ServerCallContext context)
        {
            await Task.CompletedTask;
            Console.WriteLine();
            Console.WriteLine($"@@@@@@@@@@register方法被调用，调用方：{request.Name}，站点ID{request.Guid}，{DateTime.Now}。");
            Console.WriteLine();
            return new PublisherHandle { Guid = "1010" };
        }
        public override async Task<Empty> publish(Message request, ServerCallContext context)
        {
            await Task.CompletedTask;
            Console.WriteLine();
            Console.WriteLine($"********publish方法被调用，发布标题：{request.Title}，发布内容：{request.Detail}，{DateTime.Now}。");
            Console.WriteLine();
            return new Empty();
        }
        public override async Task<Empty> ping(PublisherHandle request, ServerCallContext context)
        {
            await Task.CompletedTask;
            Console.WriteLine($"ping方法被调用，站点ID{request.Guid}，{DateTime.Now}。");
            return new Empty();
        }
    }

    class Program
    {

        public static async Task Main(string[] args)
        {
            try
            {
                Server server = new Server
                {
                    Services = { mc.MessageCenter.BindService(new MessageCenterImpl()) },
                    Ports = { new ServerPort("localhost", 9007, ServerCredentials.Insecure) }
                };
                server.Start();

                Console.WriteLine("gRPC server listening on port 9007");
                Console.WriteLine("任意键退出...");
                Console.ReadKey();

                await server.ShutdownAsync();

            }
            catch (Exception e)
            {
                Console.WriteLine($"消息中心服务异常崩溃，{e}");
                Console.WriteLine("任意键退出...");
                Console.ReadKey();
            }
        }
    }
}
